package com.clouddot.baipai.ui.fragment.V_MainFragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Paint;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.constraint.ConstraintLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.clouddot.baipai.R;
import com.clouddot.baipai.infrastructure.environment.Env;
import com.clouddot.baipai.model.beam.getArcticById.getArcticByIdResponse;
import com.clouddot.baipai.model.beam.getArcticList.ariticInfo;
import com.clouddot.baipai.model.beam.getArcticList.getArcticListResponse;
import com.clouddot.baipai.model.beam.getSchoolInfo.getSchoolInfoResponse;
import com.clouddot.baipai.ui.activity.V_MainActivity;
import com.clouddot.baipai.ui.fragment.BaseFragment;
import com.clouddot.baipai.ui.adapter.V_Adapter.V_RecyclerAdapter;
import com.clouddot.baipai.ui.dialog.V_Dialog.V_FoodDailog;
import com.clouddot.baipai.ui.util.recycleView.DivierItemLinear;
import com.clouddot.baipai.ui.util.EscapeUnescapeUtil;
import com.clouddot.baipai.ui.util.SelectedBtnUtil;
import com.clouddot.baipai.ui.util.ToastUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by wxy on 2018/4/10.
 */

public class V_SchoolFragment extends BaseFragment {

    private View view;
    private Context context;
    private HorizontalScrollView mHorizontalScrollView;
    private LinearLayout ll;
    private ImageView mImageView;
    private LinearLayout last,next;
    private ConstraintLayout constraintLayout3;
    private ConstraintLayout constraintLayout;
    private ScrollView constraintLayout4 ;
    private RecyclerView recyclerView;
    private RelativeLayout relativeLayout;
    private ImageView imageView;

    private V_RecyclerAdapter classRecyclerAdapter;
    private List<ariticInfo> list = new ArrayList<ariticInfo>();

    private float mCurrentCheckedRadioLeft; // 当前被选中的RadioButton距离左侧的距离
    private int Underline_height = 5; // 下划线高度
    private Boolean isRunning = false;
    private Button[] btnArray;
    private int buttonAmount = 4;
    private int currentTitleIndex = 0;
    private List<String> nameLists;
    int screenWidth = 751 ;
    // 总共可以放多少个字
    int count = 0;
    // textView全部字符的宽度
    float textTotalWidth = 0.0f;
    // textView一个字的宽度
    float textWidth = 0.0f;
    Paint paint = new Paint();
    private int pageCount;
    private int CurrentPage = 1;
    private String currentBtn = "FOOD";

    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        return view;
    }

    @Override
    protected void setContentView() {
        super.setContentView();

        view = LayoutInflater.from(context).inflate(R.layout.v_f_schoolfg,null);
    }

    @SuppressLint("NewApi")
    @Override
    protected void initControls() {
        super.initControls();
        nameLists = new ArrayList<>();
        nameLists.add("学校简介");
        nameLists.add("学校环境");
        nameLists.add("学校信息");
        nameLists.add("本周菜谱");
        nameLists.add("考勤制度");


        ll = view.findViewById(R.id.lay);
        mImageView =  view.findViewById(R.id.img1);
        mHorizontalScrollView = view.findViewById(R.id.horizontalScrollView);

        displayGroup();

        tvContent1 =  view.findViewById(R.id.tvContent);
        tvContent2 =  view.findViewById(R.id.tvContent2);
        imageView = view.findViewById(R.id.img);
        textWidth = tvContent1.getTextSize();

        paint.setTextSize(textWidth);
        recyclerView = view.findViewById(R.id.recycle);
        recyclerView.setLayoutManager(new LinearLayoutManager(context));
        recyclerView.addItemDecoration(new DivierItemLinear(context,DivierItemLinear.VERTICAL_LIST));
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        classRecyclerAdapter = new V_RecyclerAdapter(context,list,1);
        recyclerView.setAdapter(classRecyclerAdapter);
        relativeLayout = view.findViewById(R.id.loading);
        ImageView loading = view.findViewById(R.id.imgloading);
        loading.startAnimation(loadingAnim);
        constraintLayout3 = view.findViewById(R.id.content1);
        constraintLayout4 = view.findViewById(R.id.content2);
        last = view.findViewById(R.id.last);
        next = view.findViewById(R.id.next);
        constraintLayout = view.findViewById(R.id.content);
//        mHorizontalScrollView.startAnimation(animation4);
        constraintLayout.startAnimation(animation4);
    }

    @Override
    protected void setListener() {
        super.setListener();
        last.setOnClickListener(lastListener);
        next.setOnClickListener(nextListener);

    }

    @Override
    protected void loadParams() {
        super.loadParams();
    }

    @Override
    public void onAttach(Context context) {
        this.context = context;
        super.onAttach(context);
    }


    @Override
    public void onPause() {
        super.onPause();
        if (dailog != null) dailog.closeDialog();
    }


    @Override
    public void onResume() {
        super.onResume();
        if(Env.getAppContext().isInitial) {
            runThreadAction(btnArray[0].getText().toString());
        }

    }

    @Override
    public void runThreadAction(String actionName) {
        super.runThreadAction(actionName);
    }

    @Override
    protected Object runThreadActionExceute(String actionName) {
        super.runThreadActionExceute(actionName);
        if(actionName.equals("FOOD")) {
            return Env.getAppPresenter().getArcticList(actionName,CurrentPage,Env.getAppContext().itemCount);
        }else if(actionName.matches("[0-9]+")){
            return Env.getAppPresenter().getArcticById(actionName);
        } else {
            return Env.getAppPresenter().getSchoolInfo(actionName);
        }
    }
    private  V_FoodDailog dailog;
    @Override
    protected void runThreadActionSuccess(String actionName, Object result) {
        super.runThreadActionSuccess(actionName, result);
        if (actionName.matches("[0-9]+")) {
            getArcticByIdResponse response = (getArcticByIdResponse) result;
            if(response.isSuccess()){
                dailog  = new V_FoodDailog(context);
                List<TextView> TextViews = dailog.getTextViews();
                TextViews.get(0).setText(response.BaseData.getTitle());
                TextViews.get(1).setText(response.BaseData.getCreateTimeText());
                String str = EscapeUnescapeUtil.unescape(response.BaseData.getDetail());
                WebView webView = dailog.getWebView();
                webView.getSettings().setDefaultTextEncodingName("UTF -8");
                webView.loadData(str, "text/html; charset=UTF-8", null);
                final ImageView close = dailog.getCloseView();
                close.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        V_MainActivity.backTime = Env.getAppContext().backMainTime * 60;

                        dailog.closeDialog();
                    }
                });
                dailog.showDialog();
            }else{
                ToastUtil.showToast(context,response.getErrMsg());
            }

        } else {
            relativeLayout.setVisibility(View.GONE);
            if (actionName.equals("FOOD")) {
                final getArcticListResponse response = (getArcticListResponse) result;
                if (response.isSuccess()) {
                    if(!response.list.isEmpty()){
                        list = response.list;
                        pageCount = Integer.parseInt(response.PageCount);
                    }else {
                        list = new ArrayList<>();
                        ariticInfo infoItem = new ariticInfo();
                        infoItem.setTitle("当前没有菜谱数据");
                        infoItem.setCreateTime("");
                        list.add(infoItem);

                    }
                    classRecyclerAdapter = new V_RecyclerAdapter(context, list,1);
                    classRecyclerAdapter.setbtnOnclicker(new V_RecyclerAdapter.btnOnclicker() {
                        @Override
                        public void onClicked(int position) {
                            V_MainActivity.backTime = Env.getAppContext().backMainTime * 60;

                            runThreadAction(response.list.get(position).getId());
                        }
                    });
                    recyclerView.setAdapter(classRecyclerAdapter);
                    constraintLayout3.setVisibility(View.VISIBLE);
                } else {
                    ToastUtil.showToast(context,response.getErrMsg());
                    isRunning = true;
                    return;
                }
            } else {
                getSchoolInfoResponse response = (getSchoolInfoResponse) result;
                if (response.isSuccess()) {
                    string = String.valueOf(Html.fromHtml(EscapeUnescapeUtil.unescape(response.ArticleData.getContent())));
                    constraintLayout4.setVisibility(View.VISIBLE);
                    if (actionName.equals("考勤制度")) {
                        imageView.setVisibility(View.GONE);
                        tvContent1.setVisibility(View.GONE);
                        tvContent2.setText(string);
                    }else {
                        imageView.setVisibility(View.VISIBLE);
                        tvContent1.setVisibility(View.VISIBLE);
                        Glide.with(context).load(response.url).placeholder(R.drawable.imageload).error(R.drawable.imagefail).into(imageView);
//                        Glide.with(context).load(response.url).error(R.drawable.close).into(imageView);
                        drawImageViewDone();
                    }
                } else {
                    ToastUtil.showToast(context,response.getErrMsg());
                    isRunning = true;
                    return;
                }
            }

        }
        isRunning = true;

    }

    @Override
    protected void runThreadActionError(String actionName, Exception ex) {
        super.runThreadActionError(actionName, ex);
    }

    private TextView tvContent1,tvContent2;
    String string = null;
    private int width = 300;
    private int height = 450;
    private void drawImageViewDone() {
        tvContent2.setText("");
        tvContent1.setText("");
        int lineHeight = tvContent1.getLineHeight();
        int lineCount = (int) Math.ceil((double) height / (double) lineHeight);
        float rowWidth = screenWidth - width - tvContent1.getPaddingLeft() - tvContent1.getPaddingRight();
        int columnCount = (int) (rowWidth / textWidth);
        count = lineCount * columnCount;
        textTotalWidth = (float) ((float) count * textWidth);
        if (count <= string.length()) {
            tvContent1.setText(string.substring(0, count));
            // 检查行数是否大于设定的行数，如果大于的话，就每次减少一个字符，重新计算行数与设定的一致
            while (tvContent1.getLineCount() > lineCount) {
                count -= 1;
                tvContent1.setText(Html.fromHtml(string.substring(0, count)));
            }
            tvContent2.setText(Html.fromHtml(string.substring(count)));
        } else {
            tvContent1.setText(Html.fromHtml(string));

        }
    }


    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    private void displayGroup() {
        DisplayMetrics dm = new DisplayMetrics();
        mainActivity.getWindowManager().getDefaultDisplay().getMetrics(dm);
        int width = dm.widthPixels - 55;

        btnArray = new Button[nameLists.size()];
        android.widget.LinearLayout.LayoutParams btnArrayParams = new LinearLayout.LayoutParams(width / buttonAmount, 100);
        for (int i = 0; i < nameLists.size(); i++)
        {
            btnArray[i] = new Button(context);
            btnArray[i].setLayoutParams(btnArrayParams);
            btnArray[i].setText(nameLists.get(i));
            btnArray[i].setTextSize(26);
            btnArray[i].setTag(i);
            btnArray[i].setBackground(null);
            btnArray[i].setTextColor(gray);
            btnArray[i].setOnClickListener(onClickListener);

            ll.addView(btnArray[i]);

            if (i == 0)
            {
                btnArray[0].setSelected(true);
                btnArray[0].setTextColor(blue);
                mImageView.setLayoutParams(new LinearLayout.LayoutParams(width / buttonAmount, Underline_height));
            }
        }
    }

    /**
     * 点击套餐分组的监听器
     */
    private View.OnClickListener onClickListener = new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            if(isRunning) {
                list.clear();
                isRunning = false;
                int tag = (Integer) v.getTag();
                SelectedBtnUtil.selectedforBtn(btnArray, btnArray[tag]);
                for (Button btn : btnArray) {
                    if (btn.getText().toString().equals(btnArray[tag].getText().toString())) {
                        btn.setTextColor(blue);
                    } else {
                        btn.setTextColor(gray);
                    }
                }
                mCurrentCheckedRadioLeft = btnArray[tag].getLeft();// 更新当前蓝色横条距离左边的距离
                mHorizontalScrollView.smoothScrollTo((int) mCurrentCheckedRadioLeft - btnArray[0].getRight(), 0);
                android.widget.LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(btnArray[tag].getRight()
                        - btnArray[tag].getLeft(), Underline_height);
                params.leftMargin = (int) (tag * btnArray[0].getRight());
                mImageView.setLayoutParams(params);

                currentTitleIndex = tag;

                constraintLayout3.setVisibility(View.GONE);
                constraintLayout4.setVisibility(View.GONE);
                relativeLayout.setVisibility(View.VISIBLE);
                pageCount = 0;
                CurrentPage = 1;
                V_MainActivity.backTime = Env.getAppContext().backMainTime * 60;


                if (currentTitleIndex != 3) {
                    runThreadAction(btnArray[tag].getText().toString()); // 发送套餐列表请求

                } else {
                    pageCount = 0;
                    CurrentPage = 1;
                    runThreadAction("FOOD");
                }
            }
        }
    };

    private View.OnClickListener lastListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            V_MainActivity.backTime = Env.getAppContext().backMainTime * 60;

            if (CurrentPage <= 1){
                ToastUtil.showToast(context,"当前是第一页");
                return;
            }
            relativeLayout.setVisibility(View.VISIBLE);
            recyclerView.setVisibility(View.GONE);
            CurrentPage--;
            runThreadAction(currentBtn);
        }
    };

    private View.OnClickListener nextListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            V_MainActivity.backTime = Env.getAppContext().backMainTime * 60;

            if (CurrentPage >= pageCount){
                ToastUtil.showToast(context,"当前是最后一页");
                return;
            }
            relativeLayout.setVisibility(View.VISIBLE);
            recyclerView.setVisibility(View.GONE);
            CurrentPage++;
            runThreadAction(currentBtn);
        }
    };


}
